<template>
  <div class="chat">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <div class="titleDiv">
        <span>标题：</span>
        <input placeholder="请输入标题" v-model="title" />
      </div>
      <Editor
        style="height: 350px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div class="shareDiv">
      <el-button class="shareBtn" icon="Share" type="primary" @click="handleShareClick"
        >分享</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import useStoreStore from '@/store/main/store/store'
import { MessageBox } from '@element-plus/icons-vue'

// components: { Editor, Toolbar },
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>请输入内容...</p>')

// 标题
const title = ref('')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = '<p>请输入内容...</p>'
  }, 1500)
})

const mode = ref('default')

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const storeStore = useStoreStore()

function handleShareClick() {
  if (!title.value || !valueHtml.value) {
    ElMessage({
      message: '标题或正文不能为空',
      type: 'warning'
    })
    return
  }

  // console.log(valueHtml.value)

  const itemData = { title: title.value, content: valueHtml.value }
  storeStore
    .postMyStoreDataAction(itemData)
    .then((res) => {
      // console.log(res)
      if (res.code === 0) {
        title.value = ''
        valueHtml.value = '<p>请输入内容...</p>'
        ElMessage({
          message: '发布成功',
          type: 'success'
        })
      } else {
        ElMessage({
          message: '发布失败',
          type: 'warning'
        })
      }
    })
    .catch(() => {
      ElMessage({
        message: '发布失败',
        type: 'warning'
      })
    })
}
</script>

<style scoped>
.shareDiv {
  text-align: center;
  padding: 10px;
}
.titleDiv {
  background-color: rgba(108, 184, 184, 0.881);
  padding: 15px 10px;
}
</style>
